package cn.edu.mju.controller;

import cn.edu.mju.Utils.EncryptUtils;
import cn.edu.mju.Utils.ResultData;
import cn.edu.mju.pojo.User;
import cn.edu.mju.service.UserService;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService userService;



    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        if(session.getAttribute("LOGIN_USER")!=null) {
            return "admin";
        }
        return "login";
    }


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ResultData login(String username, String password, HttpServletRequest request){

        //实例化加密工具类
        EncryptUtils encryptUtils =new  EncryptUtils();
        //加密后的密码
        String en_password = encryptUtils.md5(password);

        //封装成用户类
        User U = new User();
        U.setUsername(username);
        U.setPassword(en_password);

        if(userService.login(U)){
            HttpSession session = request.getSession(true);
            session.setAttribute("LOGIN_USER", U);
            return ResultData.fail("200","登录成功");
        }
        return ResultData.fail("403","登录失败");
    }


    @RequestMapping("/quit")
    public String quit(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.removeAttribute("LOGIN_USER");
        if(session.getAttribute("LOGIN_USER")==null) {
            return "login";
        }
        return "admin";
    }

//    @RequestMapping("/findUserById/{id}")
//    @ResponseBody
//    public String findUserById(@PathVariable String id){
//
//        User user = userService.queryUser(Long.parseLong(id));
//
//        return JSONObject.toJSONString(user);
//    }
//
//    @RequestMapping("/select")
//    public ModelAndView selectUser() throws Exception {
//        ModelAndView mv = new ModelAndView();
//        User user = userService.queryUser(1);
//        mv.addObject("user", user);
//        mv.setViewName("user");
//        return mv;
//    }




}
